package tsp;

import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.xerces.parsers.DOMParser;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class GPXParser
{
	private List<Waypoint> wayPoints = new ArrayList<Waypoint>();

	private String gpxFileContents = "";
	private Document gpxDOM = null;

	public GPXParser(String gpxFileContents) throws SAXException, IOException
	{
		this.gpxFileContents = gpxFileContents;

		extractWaypoints();
	}

	public List<Waypoint> getWaypoints()
	{
		return wayPoints;
	}

	private void extractWaypoints() throws SAXException, IOException
	{
		DOMParser parser = new DOMParser();
		parser.parse(new InputSource(new StringReader(gpxFileContents)));
		gpxDOM = parser.getDocument();

		NodeList allWptNodes = gpxDOM.getElementsByTagName("wpt");

		int wptNodeCount = allWptNodes.getLength();
		for (int nodeNum = 0; nodeNum < wptNodeCount; ++nodeNum)
		{
			Node wptNode = allWptNodes.item(nodeNum);

			NamedNodeMap noticeAttributes = wptNode.getAttributes();
			Node latAttribute = noticeAttributes.getNamedItem("lat");
			Node longAttribute = noticeAttributes.getNamedItem("lon");

			String latitude = latAttribute.getNodeValue();
			String longitude = longAttribute.getNodeValue();

			NodeList wptChildNodes = wptNode.getChildNodes();

			String cacheName = "";
			String cacheDesc = "";

			int wptNodeSize = wptChildNodes.getLength();
			for (int x = 0; x < wptNodeSize; ++x)
			{
				Node childNode = wptChildNodes.item(x);

				if (childNode.getNodeName().equalsIgnoreCase("name"))
					cacheName = childNode.getTextContent();
				
				if (childNode.getNodeName().equalsIgnoreCase("desc"))
					cacheDesc = childNode.getTextContent();
			}

			/* Now create and add a new waypoint for this cache */ 
			Waypoint wp = new Waypoint(Double.valueOf(latitude), Double.valueOf(longitude), cacheName, cacheDesc);		
			wayPoints.add(wp);
		}
	}
}
